package com.xd.user.controller;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xd.common.model.R;
import com.xd.common.base.BaseController;
import com.xd.common.constant.CommonConstant;
import com.xd.user.api.entity.Department;
import com.xd.user.api.entity.DepartmentHeader;
import com.xd.user.api.feign.DepartmentClient;
import com.xd.user.service.DepartmentHeaderService;
import com.xd.user.service.DepartmentService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限(Department)表控制层
 *
 * @author hbx
 * @since 2020-06-28 12:34:33
 */
@RestController
@RequestMapping("department")
@Transactional(rollbackFor = Exception.class)
public class DepartmentController extends BaseController<DepartmentService, Department, String> implements DepartmentClient {

    @Resource
    private DepartmentService DepartmentService;

    @Resource
    private DepartmentHeaderService departmentHeaderService;


    /**
     * @return R<List < Department>>
     * @author huboxin
     * @description: TODO 获取部门树
     * @date 8:44 2020/6/29
     **/
    @GetMapping("getTree")
    @ApiOperation(value = "获取部门树", notes = "获取部门树")
    public R<List<Department>> getTree() {
        List<Department> list = DepartmentService.list();
        list = createTree(list, "0", "一级部门");
        return success(list);
    }


    /**
     * @param department 部门信息
     * @return com.baomidou.mybatisplus.extension.api.R<java.lang.Boolean>
     * @author huboxin
     * @description: TODO 修改重置部门
     * @date 18:29 2020/7/3
     **/
    @PostMapping("restartDept")
    @ApiOperation(value = "修改重置部门", notes = "修改重置部门")
    public R<Boolean> restartDept(@RequestBody @ApiParam("部门信息") Department department) {
        //删除原部门用户关联
        departmentHeaderService.remove(Wrappers.<DepartmentHeader>lambdaQuery()
                .eq(DepartmentHeader::getDepartmentId, department.getId()));
        List<String> viceHeader = department.getViceHeader();
        List<String> mainHeader = department.getMainHeader();
        List<DepartmentHeader> departmentHeaders = new ArrayList<>();
        //添加关联表
        viceHeader.forEach(s -> departmentHeaders.add(
                new DepartmentHeader().setType(CommonConstant.HEADER_TYPE_VICE)
                        .setDepartmentId(department.getId())
                        .setUserId(s)));
        mainHeader.forEach(s -> departmentHeaders.add(
                new DepartmentHeader().setType(CommonConstant.HEADER_TYPE_MAIN)
                        .setDepartmentId(department.getId())
                        .setUserId(s)));
        if (!departmentHeaderService.saveBatch(departmentHeaders)) {
            return failed("修改部门失败");
        }
        return this.service.updateById(department) ? success(true) : failed("修改部门失败");
    }

    /**
     * 创建部门树
     *
     * @param list     list
     * @param parentId parentId
     * @return List<Department>
     */
    public List<Department> createTree(List<Department> list, String parentId, String parentTitle) {
        List<Department> objects = new ArrayList<>();
        list.forEach(department -> {
            if (parentId.equals(department.getParentId())) {
                List<Department> tree = createTree(list, department.getId(), department.getTitle());
                //排序
                tree.sort(Comparator.comparing(Department::getSortOrder));
                //查询关联的用户信息
                List<DepartmentHeader> departmentHeaders = departmentHeaderService.list(Wrappers.<DepartmentHeader>lambdaQuery()
                        .eq(DepartmentHeader::getDepartmentId, department.getId()));
                //分主副职位
                List<String> viceUsers = departmentHeaders.stream()
                        .filter(departmentHeader -> CommonConstant.HEADER_TYPE_VICE.equals(departmentHeader.getType()))
                        .map(DepartmentHeader::getUserId)
                        .collect(Collectors.toList());
                List<String> mainUsers = departmentHeaders.stream()
                        .filter(departmentHeader -> CommonConstant.HEADER_TYPE_MAIN.equals(departmentHeader.getType()))
                        .map(DepartmentHeader::getUserId)
                        .collect(Collectors.toList());
                department.setViceHeader(viceUsers);
                department.setMainHeader(mainUsers);
                department.setDepartments(tree);
                department.setParentTitle(parentTitle);
                objects.add(department);
            }
        });
        return objects;
    }
}
